﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevTeam;
using Fatura.DevTeam;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace Fatura
{
    public partial class Login : XtraForm
    {
        public string DB;
        Color DefaultColor;
        string DatabaseNamePostFix = "";

        public Login()
        {
            InitializeComponent();

            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle("Office 2013 Light Gray");
        }

        private void Login_Load(object sender, EventArgs e)
        {
            DefaultColor = cbDatabase.BackColor;
            cbDatabase.Text = "PRODUCTION";
            cbDatabase.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            this.AcceptButton = btnLogin;

            cbDatabase.SelectedIndexChanged += new System.EventHandler(this.cbDatabase_SelectedIndexChanged);
            btnLogin.Click += new EventHandler(btnLogin_Click);
            this.Shown += new EventHandler(Login_Shown);
            lnkBaslatmaSorunu.OpenLink += new OpenLinkEventHandler(lnkBaslatmaSorunu_OpenLink);
            this.KeyPreview = true;
            this.KeyDown += new KeyEventHandler(Login_KeyDown);

            Dictionary<string, string> SavedLookups = new Dictionary<string, string>();
            
            Session.Init( new Options(), SavedLookups, (int)Rp.V_User);
        }

        void Login_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.F12)
            {
                if (File.Exists(Session.SQLiteFile))
                    File.Delete(Session.SQLiteFile);
                XtraMessageBox.Show("Tekrar login olmayı deneyin.");
            }
        }

        private void lnkBaslatmaSorunu_OpenLink(object sender, OpenLinkEventArgs e)
        {

            if (XtraMessageBox.Show("Programı başlatmakta sorun mu yaşıyorsunuz?", "System", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                if (File.Exists(Session.SQLiteFile))
                    File.Delete(Session.SQLiteFile);
                XtraMessageBox.Show("Tekrar login olmayı deneyin.");
            }
        }


        private void btnLogin_Click(object sender, EventArgs e)
        {
            DoLogin();
        }

        private void Login_Shown(object sender, EventArgs e)
        {
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                this.Text += " - v" + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();

            string userName = RememberUser();
            if (userName != String.Empty)
            {
                txtUsername.Text = userName;
                txtPassword.Text = FileManager.ReadText(Session.AppDataPath + "\\oku.txt").Replace(Environment.NewLine, string.Empty);
                txtPassword.Focus();

                switch (Environment.MachineName.ToUpper())
                {
                    case "ORHAN-PC":
                        cbDatabase.SelectedIndex = 1;
                        //btnLogin.PerformClick();
                        break;

                    case "KGULCAN":
                        cbDatabase.SelectedIndex = 1;

                        FileInfo fi = new FileInfo(@"D:\Karbel\Erişim\ce.txt");
                        if (fi.Exists)
                            txtPassword.Text = File.ReadAllText(fi.FullName);
                        break;

                    case "KADIR-PC":
                        cbDatabase.SelectedIndex = 1;
                        break;
                }
            }
            else
                txtUsername.Focus();
        }

        private void DoLogin()
        {
            if (CheckCredentials(txtUsername.Text, txtPassword.Text))
            {
                if (Session.CurrentUser.PasswordHash == "1" ||
                    Session.CurrentUser.PasswordHash == string.Empty)
                    lnkChangePassword_OpenLink(null, null);
                else
                    this.DialogResult = DialogResult.OK;
            }
            else if (pnlLogin.Enabled)
            {
                txtPassword.Text = String.Empty;
                txtPassword.Focus();
            }
        }

        private string RememberUser(string UserNameToSave = "")
        {
            try
            {
                RegistryKey register = Registry.CurrentUser.CreateSubKey(@"Software\ConfExpert");
                if (UserNameToSave != "")
                {
                    register.SetValue("UserLastLoggedIn", UserNameToSave, RegistryValueKind.String);
                    Registry.LocalMachine.Flush();
                }
                else
                    UserNameToSave = (string)register.GetValue("UserLastLoggedIn", String.Empty);

            }
            catch (Exception)
            {
            }
            return UserNameToSave;
        }

        private void cbDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbDatabase.BackColor = cbDatabase.SelectedIndex > 0 ? Color.YellowGreen : DefaultColor;
        }

        private void lnkChangePassword_OpenLink(object sender, OpenLinkEventArgs e)
        {
            //TODO
            //using (ChangePassword cp = new ChangePassword(txtUsername.Text, DatabaseNamePostFix))
            //    cp.ShowDialog();
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Abort;
        }

        public bool CheckCredentials(string Username, string Password)
        {
            Session.ServerAddress = "confexpert.karbel.com";

            ceGateSoapClient gate = new ceGateSoapClient();
            gate.Endpoint.Address = new System.ServiceModel.EndpointAddress(string.Format("http://{0}/ceGate/ceGate.asmx", Session.ServerAddress));

            SqlConnectionStringBuilder cnnStrBuilder = new SqlConnectionStringBuilder();
            DataSet dsCredentials = null;
            try
            {
                dsCredentials = gate.GetCredentials(Username, Password, Session.ServerAddress, DatabaseNamePostFix);
            }
            catch (Exception ex)
            {
                LogManager.LogToDB(ex);
                //XtraMessageBox.Show("Sistem Hatası ! [ConfExpert Gate]:" + ex.ToString());
                return false;
            }

            if (dsCredentials == null)
                return false;

            string connectionString = dsCredentials.Tables["ConnectionString"].Rows[0]["ConnectionString"].ToString();
            cnnStrBuilder.ConnectionString = connectionString;
            
            Session.DataManager = new DataManager(cnnStrBuilder.ConnectionString);

            try
            {

                DataRow dr = dsCredentials.Tables["User"].Rows[0];

                Session.CurrentUser = new User();
                Session.CurrentUser.UserId = (int)dr["UserId"];
                Session.CurrentUser.InitialUserId = Session.CurrentUser.UserId;
                Session.CurrentUser.DepartmentId = (int)dr["DepartmentId"];
                Session.CurrentUser.UserName = Username;
                Session.CurrentUser.Name = dr["Name"].ToString();
                Session.CurrentUser.Email = dr["Email"].ToString();
                Session.CurrentUser.PasswordHash = dr["PasswordHash"].ToStr();
                Session.Settings = PrgSettings.LoadSettings(dr["Settings"].ToString());
                Session.PrgSettingsOrg = PrgSettings.LoadSettings(dr["Settings"].ToString());

                Session.ApplicationName = "Fatura";
                Session.GetLookupMapSp = "FT_GetLookupMap";

                RememberUser(Username);

                double EUR = 1, USD = 1, GBP = 1;
                List<string> exchange = new List<string>();
                foreach (DataRow dr2 in dsCredentials.Tables["Currency"].Rows)
                {
                    exchange.Add(dr2["Currency"].ToString() + ": " + dr2["Buying"].ToString());
                    string currency = dr2["Currency"].ToString();
                    double val = double.Parse(dr2["Buying"].ToString());
                    switch (currency)
                    {
                        case "EUR": EUR = val; break;
                        case "USD": USD = val; break;
                        case "GBP": GBP = val; break;
                    }
                }

                exchange.Add(String.Format("EUR/USD: {0:#.####}", EUR / USD));
                Session.GununKurlari = "* " + string.Join("  " + ((char)183) + "  ", exchange.ToArray());
                Session.Usd = USD; Session.Eur = EUR; Session.Gbp = GBP;

                DataRow[] serviceInfo = dsCredentials.Tables["Services"].Select("Id='Messenger'");
                if (serviceInfo.Length > 0)
                {
                    Session.MessengerUserName = serviceInfo[0]["Username"].ToStr();
                    Session.MessengerPassword = serviceInfo[0]["Password"].ToStr();
                }

                return true;
            }

            catch (Exception Ex)
            {
                XtraMessageBox.Show("Sistem Hatası ! [Login]:" + Ex.ToString());
            }

            return false;
        }

        private void cbDatabase_EditValueChanged(object sender, EventArgs e)
        {
            DatabaseNamePostFix = (!Session.isProduction ? "Test" : "");
            Session.SQLiteFile = Session.AppDataPath + "\\" + DatabaseNamePostFix + "ce.sqlite";
        }

       
    }
}
